﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects.DataClasses;
using System.Reflection;
using Util;
using DAL;
using System.Configuration;

namespace UtilLibrary
{
    public class DbUtil
    {
        private static Model1Container dbContainer = null;
        static DbUtil()
        {
            dbContainer = new Model1Container();
        }

        public static Model1Container GetDbContainer()
        {
            return new Model1Container();
            //String connStr = ConfigurationManager.AppSettings["env"] == "test" ? "name=Model1Container" : "name=productContainer";
            //return new Model1Container(connStr);
        }

        public static void DataEntityToBizObjTrans(EntityObject pEntity, BaseBizEntity pBizEntity)
        {
            try
            {
                foreach (PropertyInfo pro1 in pEntity.GetType().GetProperties())
                {
                    Type entityType = pEntity.GetType();
                    foreach (PropertyInfo pro2 in pBizEntity.GetType().GetProperties())
                    {
                        if (pro2.Name.ToLower() == pro1.Name.ToLower())
                        {
                            pro2.GetType();
                            Type enumType = pro2.PropertyType;
                            if (pro2.PropertyType.IsEnum && enumType == null)
                            {
                                throw new Exception("没有找到枚举类型：" + pro2.Name);
                            }
                            object value = pro2.PropertyType.IsEnum ? Enum.Parse(enumType, pro1.GetValue(pEntity, null).ToString()) : pro1.GetValue(pEntity, null);
                            pro2.SetValue(pBizEntity, value, null);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }

        public static void BizObjTransToDataEntity(BaseBizEntity pBizEntity, EntityObject pEntity)
        {
            foreach (PropertyInfo pro1 in pBizEntity.GetType().GetProperties())
            {
                Type entityType = pEntity.GetType();
                foreach (PropertyInfo pro2 in pEntity.GetType().GetProperties())
                {
                    if (pro2.Name.ToLower() == pro1.Name.ToLower())
                    {
                        Type enumType = pro2.PropertyType;
                        object value = pro1.PropertyType.IsEnum ? pro1.GetValue(pBizEntity, null).ToString() : pro1.GetValue(pBizEntity, null);
                        pro2.SetValue(pEntity, value, null);
                    }
                }
            }
        }

        public static String ConcatEntityNameSet(string pEntityName)
        {
            return ConstLib.MODEL1CONTAINER + "." + pEntityName;
        }
    }
}
